<template>
  <div class="menu-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <div>
            <el-button @click="handleRefresh">刷新</el-button>
            <el-button type="primary" @click="handleAddRoot">新增根菜单</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="菜单名称">
          <el-input v-model="searchForm.menuName" placeholder="请输入菜单名称" clearable />
        </el-form-item>
        <el-form-item label="菜单路径">
          <el-input v-model="searchForm.menuPath" placeholder="请输入菜单路径" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 菜单树表格 -->
      <div class="menu-tree">
        <el-table
            :data="menuTreeData"
            row-key="menuId"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            v-loading="loading"
            border
            stripe
        >
          <el-table-column prop="menuName" label="菜单名称" min-width="200">
            <template #default="{ row }">
              <span style="margin-left: 5px;">
                <el-icon v-if="row.menuIcon" style="vertical-align: middle; margin-right: 5px;">
                  <component :is="getIconComponent(row.menuIcon)" />
                </el-icon>
                {{ row.menuName }}
                <el-tag v-if="row.parentId === 0" size="small" type="info" style="margin-left: 8px;">
                  根菜单
                </el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="menuPath" label="菜单路径" width="180" />
          <el-table-column prop="menuSort" label="排序" width="80" align="center" />
          <el-table-column prop="isVisible" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isVisible === 1 ? 'success' : 'info'" size="small">
                {{ row.isVisible === 1 ? '显示' : '隐藏' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="menuComponent" label="组件路径" width="200" />
          <el-table-column prop="createTime" label="创建时间" width="180" align="center">
            <template #default="{ row }">
              {{ formatTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" @click="handleAddChild(row)">添加子菜单</el-button>
              <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 菜单表单对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        @close="handleDialogClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
              v-model="form.parentId"
              :data="menuOptions"
              :props="treeSelectProps"
              check-strictly
              placeholder="选择父级菜单"
              style="width: 100%"
              :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="menuPath">
          <el-input v-model="form.menuPath" placeholder="请输入菜单路径" />
          <div class="form-tip">前端路由路径，如：/user</div>
        </el-form-item>
        <el-form-item label="菜单图标" prop="menuIcon">
          <el-input v-model="form.menuIcon" placeholder="请输入图标名称（如：User）">
            <template #append>
              <el-button @click="showIconDialog = true">选择图标</el-button>
            </template>
          </el-input>
          <div class="form-tip">Element Plus 图标名称</div>
        </el-form-item>
        <el-form-item label="组件路径" prop="menuComponent">
          <el-input v-model="form.menuComponent" placeholder="请输入组件路径" />
          <div class="form-tip">Vue组件路径，如：User</div>
        </el-form-item>
        <el-form-item label="排序" prop="menuSort">
          <el-input-number v-model="form.menuSort" :min="0" :max="999" />
          <div class="form-tip">数字越小排序越靠前</div>
        </el-form-item>
        <el-form-item label="显示状态">
          <el-radio-group v-model="form.isVisible">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 图标选择对话框 -->
    <el-dialog title="选择图标" v-model="showIconDialog" width="800px">
      <div class="icon-list">
        <div
            v-for="icon in iconList"
            :key="icon"
            class="icon-item"
            :class="{ 'icon-item-active': form.menuIcon === icon }"
            @click="selectIcon(icon)"
        >
          <el-icon size="20">
            <component :is="getIconComponent(icon)" />
          </el-icon>
          <span class="icon-name">{{ icon }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="showIconDialog = false">取消</el-button>
        <el-button type="primary" @click="showIconDialog = false">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllMenus, addMenu, updateMenu, deleteMenu } from '@/utils/menu'

// 导入图标
import {
  Odometer, Plus, Picture, StarFilled, Sell, ShoppingCart,
  Menu, Goods, User, List, Lock, Setting, Edit, Delete,
  Search, Refresh, CirclePlus, Tools, Promotion, Monitor,
  Histogram, DataBoard, CreditCard, Box, Collection
} from '@element-plus/icons-vue'

const loading = ref(false)
const submitLoading = ref(false)
const menuTreeData = ref([])
const menuOptions = ref([])
const showIconDialog = ref(false)

const searchForm = reactive({
  menuName: '',
  menuPath: ''
})

const form = reactive({
  menuId: null,
  parentId: 0,
  menuName: '',
  menuPath: '',
  menuIcon: '',
  menuSort: 0,
  menuComponent: '',
  isVisible: 1
})

const rules = {
  menuName: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 20, message: '菜单名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  menuPath: [
    { required: true, message: '请输入菜单路径', trigger: 'blur' }
  ],
  menuSort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)
const formRef = ref()

const treeSelectProps = {
  value: 'menuId',
  label: 'menuName',
  children: 'children'
}

// 图标列表
const iconList = [
  'Odometer', 'Plus', 'Picture', 'StarFilled', 'Sell', 'ShoppingCart',
  'Menu', 'Goods', 'User', 'List', 'Lock', 'Setting', 'Edit', 'Delete',
  'Search', 'Refresh', 'CirclePlus', 'Tools', 'Promotion', 'Monitor',
  'Histogram', 'DataBoard', 'CreditCard', 'Box', 'Collection'
]

// 图标映射
const iconComponents = {
  Odometer, Plus, Picture, StarFilled, Sell, ShoppingCart,
  Menu, Goods, User, List, Lock, Setting, Edit, Delete,
  Search, Refresh, CirclePlus, Tools, Promotion, Monitor,
  Histogram, DataBoard, CreditCard, Box, Collection
}

const getIconComponent = (iconName) => {
  return iconComponents[iconName] || ''
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

// 获取菜单树
const getMenuTreeData = async () => {
  loading.value = true
  try {
    const res = await getAllMenus()
    menuTreeData.value = res.data || []

    // 构建树形选择器选项（添加根节点）
    menuOptions.value = [
      {
        menuId: 0,
        menuName: '根目录',
        children: menuTreeData.value
      }
    ]
  } catch (error) {
    console.error('获取菜单树失败:', error)
    ElMessage.error('获取菜单树失败')
    menuTreeData.value = []
    menuOptions.value = []
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 这里可以实现搜索逻辑，暂时先刷新
  getMenuTreeData()
}

// 重置
const handleReset = () => {
  searchForm.menuName = ''
  searchForm.menuPath = ''
  getMenuTreeData()
}

// 刷新
const handleRefresh = () => {
  getMenuTreeData()
}

// 新增根菜单
const handleAddRoot = () => {
  dialogTitle.value = '新增根菜单'
  isAdd.value = true
  Object.keys(form).forEach(key => {
    if (key === 'parentId') {
      form[key] = 0
    } else if (key === 'menuSort') {
      form[key] = 0
    } else if (key === 'isVisible') {
      form[key] = 1
    } else {
      form[key] = ''
    }
  })
  dialogVisible.value = true
}

// 新增子菜单
const handleAddChild = (row) => {
  dialogTitle.value = '新增子菜单'
  isAdd.value = true
  Object.keys(form).forEach(key => {
    if (key === 'parentId') {
      form[key] = row.menuId
    } else if (key === 'menuSort') {
      form[key] = 0
    } else if (key === 'isVisible') {
      form[key] = 1
    } else {
      form[key] = ''
    }
  })
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = (row) => {
  dialogTitle.value = '编辑菜单'
  isAdd.value = false
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 删除菜单
const handleDelete = (row) => {
  // 检查是否有子菜单
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该菜单下有子菜单，请先删除子菜单')
    return
  }

  ElMessageBox.confirm(`确定删除菜单 "${row.menuName}" 吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      await deleteMenu(row.menuId)
      ElMessage.success('删除成功')
      getMenuTreeData()
    } catch (error) {
      console.error('删除菜单失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }).catch(() => {})
}

// 选择图标
const selectIcon = (icon) => {
  form.menuIcon = icon
}

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    if (isAdd.value) {
      await addMenu(form)
      ElMessage.success('新增菜单成功')
    } else {
      await updateMenu(form)
      ElMessage.success('更新菜单成功')
    }

    dialogVisible.value = false
    getMenuTreeData()
  } catch (error) {
    console.error('操作失败:', error)
    if (error.errors) {
      return
    }
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

onMounted(() => {
  getMenuTreeData()
})
</script>

<style scoped>
.menu-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.menu-tree {
  margin-top: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.icon-list {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 10px;
  max-height: 400px;
  overflow-y: auto;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.icon-item:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.icon-item-active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.icon-name {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
}

:deep(.el-table .el-table__row) {
  cursor: pointer;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
